package com.xnkf.common.spring.reqcheck;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.MethodDispathServlet;

import com.alibaba.fastjson.JSON;
import com.xnkf.common.spring.reqcheck.exception.DataParserException;
import com.xnkf.common.util.Constants;
import com.xnkf.common.util.ReqUtils;
import com.xnkf.common.util.RetCode;

/**
 * @ClassName: MyCheckMethodDispathServlet
 * @Description: TODO
 * @author xaoyaoyao
 * @date 2017年7月23日 下午1:03:16
 */
public class MyCheckMethodDispathServlet extends MethodDispathServlet {

	private static final long serialVersionUID = 1L;

	private static final Logger LOGGER = LoggerFactory.getLogger(MyCheckMethodDispathServlet.class);

	protected boolean checkMappHander(HttpServletRequest request, HttpServletResponse response, Object handler) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("hander is " + handler + " handler class is :" + handler.getClass());
		}
		boolean checkResult = true;
		try {
			Object result = request.getAttribute(Constants.INTER_PARAMTER);
			if (null != result && result instanceof String) {
				request.setAttribute(Constants.INTER_PARAMTER, JSON.parse(result.toString()));
				return true;
			}
			JSON jreq = ReqUtils.getReqJson(request);
			request.setAttribute(Constants.INTER_PARAMTER, jreq);
		} catch (DataParserException ex) {
			LOGGER.error("请求数据不正确", ex);
			checkResult = false;
			ReqUtils.writeError(RetCode.REQUEST_DATA_FORMAT_ERR, "请求数据格式不正确", response);
		} catch (Exception ex) {
			LOGGER.error("出错了", ex);
			checkResult = false;
			ReqUtils.writeError(RetCode.SYSERROR, "网络繁忙", response);
		}
		return checkResult;
	}
}